#ifndef PAGE_MAP_H
#define PAGE_MAP_H

#include "Common.h"
#include <iostream>

template <int BITS>
class TCMalloc_Map2
{
private:
    // 第一层的位数
    static const size_t ROOT_BIT = 12;
    // 第一层的数组长度
    static const size_t ROOT_LENGTH = 1 << ROOT_BIT;
    // 叶子节点的位数
    static const size_t LEAF_BIT = BITS - 12;
    // 叶子节点的数组长度
    static const size_t LEAF_LENGTH = 1 << LEAF_BIT;

    void ***_root;

public:
    explicit TCMalloc_Map2()
    {
        // 申请第一层的数组
        size_t size = sizeof(void **) * (1 << ROOT_BIT);
        size_t alignSize = SizeClass::_roundUp(size, 1 << PAGE_SHIFT);
        _root = (void ***)systemAlloc(alignSize >> PAGE_SHIFT);
    }

    // 根据页号获取span
    Span *get(size_t pageId)
    {
        size_t topI = (pageId >> LEAF_BIT) & 0xfff;
        if(_root[topI] == nullptr)
            return nullptr;
        size_t leafI = (pageId) & 0xffffff;
        return (Span *)_root[topI][leafI];
    }

    void set(size_t pageId, void *span)
    {
        size_t topI = (pageId >> LEAF_BIT) & 0xfff;
        ensure(topI);
        size_t leafI = pageId & 0xffffff;
        _root[topI][leafI] = span;
    }

    void ensure(size_t idx)
    {
        if(!_root[idx]){
           size_t size = sizeof(void *) * (1 << LEAF_BIT);
           size_t alignSize = SizeClass::_roundUp(size, 1 << PAGE_SHIFT);
           _root[idx] = (void **)systemAlloc(alignSize >> PAGE_SHIFT);
           
        }
    }
};

#endif